import { LOGIN_URL, ROUTER_WHITE_LIST } from "@/@CORE/app-config/config";
import { $themeConfig } from "@/@CORE/app-config";
import NProgress from "@/@CORE/app-config/nprogress";
import { initDynamicRouter } from "@/router/dynamicRouter";
import { GlobalStore } from "@/stores";
import { AuthStore } from "@/stores/modules/auth";

export default router => {
	router.beforeEach(async (to, from, next) => {
		const globalStore = GlobalStore();
		const useAuth = AuthStore();

		NProgress.start(); // 开启进度条
		const title = $themeConfig.app.appName;
		document.title = to.meta.title ? `${to.meta.title} - ${title}` : title;
		// 设置当前激活的菜单
		globalStore.SET_ACTIVEMENU(to.name);
		// 判断如果访问的是登录页面，且Token存在，保持当前页,没有Token则重置路由放行至登录页
		if (to.path == LOGIN_URL) {
			if (globalStore.token) return next(from.fullPath);
			router.resetRouter();
			return next();
		}
		// 判断访问页面是否在路由白名单内,如果在则放行
		if (ROUTER_WHITE_LIST.includes(to.path)) return next();
		// 判断是否有 Token，没有重定向到 login
		if (!globalStore.token) return next({ path: LOGIN_URL, replace: true });
		// 如果没有菜单列表，就重新请求菜单列表并添加动态路由
		try {
			await useAuth.setRouteName(to.name);
			if (!useAuth.authMenuListGet.length) {
				await initDynamicRouter();
				return next({ ...to, replace: true });
			} else {
				// 如果有菜单列表，就判断是否有权限访问该页面
				// const hasPermission = useAuth.flatMenuListGet.some(item => item.name === to.name);
				// if (hasPermission) {
				// 	return next();
				// } else {
				// 	return next({ path: "/401", replace: true });
				// }
			}
		} catch (error) {
			console.log(error, "error");
		}
		// 正常访问
		// 重定向到 404 页面

		next();
	});
	router.afterEach(() => {
		NProgress.done();
	});
	router.onError(() => {
		NProgress.done();
	});
};
